package list;

import java.util.Iterator;

/**
 * description:
 * author:张腾
 * date:2021-04-03
 */

/**
 * 队列 先进先出 使用链表实现
 * @param <T>
 */
public class Queue<T> implements Iterable<T>{
    private Node head;
    private Node last;
    private int N;

    private class Node{
        public T item;
        public Node next;

        public Node(T item,Node next){
            this.item = item;
            this.next = next;
        }
    }

    public Queue(){
        this.head = new Node(null,null);
        this.last = null;
        this.N = 0;
    }

    public boolean isEmpty(){
        return N==0;
    }

    public int size(){
        return N;
    }

    //向队列插入一个元素t
    public void enqueue(T t){
        if (last == null){
            last = new Node(t,null);
            head.next = last;
        }else {
            Node oldLast = last;
            last = new Node(t,null);
            oldLast.next = last;
        }
        N++;
    }

    //从队列中拿出一个元素
    public T dequeue(){
        if (isEmpty()){
            return null;
        }

        Node oldFirst = head.next;
        head.next = oldFirst.next;
        N--;

        if (isEmpty()){
            last = null;
        }
        return oldFirst.item;
    }


    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator{
        private Node n;

        public QIterator(){
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }
}
